package com.hl.toolkit.pay.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.demo.trade.utils.ZxingUtils;
import com.chuanglan.demo.SmsSendChuangLan;
import com.suning.demo.BatchWithdrawDemo;
import com.suning.util.Util;
import com.tycoin.SpringContextHolder;
import com.tycoin.account.slaveentity.*;
import com.tycoin.account.slaveservice.*;
import com.tycoin.common.bean.PageInfo;
import com.tycoin.common.entity.Page;
import com.tycoin.setting.slaveentity.TycoinChuanglanMsg;
import com.tycoin.setting.slaveservice.TycoinChuanglanMsgService;
import com.tycoin.user.slaveentity.TycoinUser;
import com.tycoin.user.slaveentity.TycoinUserBank;
import com.tycoin.user.slaveentity.TycoinUserRealnamePic;
import com.tycoin.user.slaveservice.TycoinUserBankService;
import com.tycoin.user.slaveservice.TycoinUserRealnamePicService;
import com.tycoin.user.slaveservice.TycoinUserService;
import com.util.*;
import com.youtu.Verification;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 
 * 支付宝支付
 */
@Controller
@RequestMapping(value = { "/" })
public class HomeController {

	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

	@Autowired
	private TycoinUserService tycoinUserService;

	@Autowired
	private TycoinAccountRechargeService tycoinAccountRechargeService;

	@Autowired
	private TycoinChuanglanMsgService tycoinChuanglanMsgService;

	@Autowired
	private TycoinAccountService tycoinAccountService;

	@Autowired
	private TycoinUserBankService tycoinUserBankService;

	@Autowired
	private TycoinUserRealnamePicService tycoinUserRealnamePicService;

	@Autowired
	private TycoinAccountCashService tycoinAccountCashService;
	
//	@Autowired
//	private TycoinAccountCashBankViewService tycoinAccountCashBankViewService;
//	

	@Autowired
	private TycoinAccountPaymentService tycoinAccountPaymentService;
	
	
  	
	@Autowired
	private TycoinUserTransferAccountService tycoinUserTransferAccountService;
	
	@Autowired
	private TycoinAccountLogService tycoinAccountLogService;
	
	@Autowired
	private TycoinAccountRechargeCallbackProcessService tycoinAccountRechargeCallbackProcessService;
	
	@RequestMapping({ "/MP_verify_llQ3JeCj5iDvoAWw.txt" })
	public void MP_verify_llQ3JeCj5iDvoAWw(HttpServletRequest request, HttpServletResponse response) throws IOException {
 	      try {
              String encoding="UTF-8";
              String filePath=SpringContextHolder.getRootRealPath()+"/MP_verify_llQ3JeCj5iDvoAWw.txt";
              File file=new File(filePath);
              if(file.isFile() && file.exists()){ //判断文件是否存在
                  InputStreamReader read = new InputStreamReader(
                  new FileInputStream(file),encoding);//考虑到编码格式
                  BufferedReader bufferedReader = new BufferedReader(read);
                  String lineTxt = null;
                  while((lineTxt = bufferedReader.readLine()) != null){
                      System.out.println(lineTxt);
          			response.getWriter().write(lineTxt);
                  }
                  read.close();
      }else{
          System.out.println("找不到指定的文件");
      }
      } catch (Exception e) {
          System.out.println("读取文件内容出错");
          e.printStackTrace();
      }

	}
	
	
	
	@RequestMapping({ "{templateCode}" })
	public String templateCode(@PathVariable("templateCode") String templateCode, Model model,
			HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		String userId = String.valueOf(request.getSession().getAttribute("userId"));
		TycoinUser tycoinUser = null;
		if ("app_systemSuccess".equals(templateCode)) {
			return "/" + templateCode;
		}
		if ("app_systemFail".equals(templateCode)) {
			return "/" + templateCode;
		}
		if ("printReceiptShow".equals(templateCode)) {
			return "/" + templateCode;
		}
		
		
		if ("printReceipt".equals(templateCode)) {
			return "/" + templateCode;
		}
		if ("app_payTwo".equals(templateCode))
			return "/" + templateCode;
		if ("app_payIndex".equals(templateCode)) {
			return "/" + templateCode;
		}
		if ("app_findpassword".equals(templateCode)) {
			return "/" + templateCode;
		}if ("app_countLogDetail2".equals(templateCode)) {
			return "/" + templateCode;
		}
		if ("app_foldLine".equals(templateCode)) {
			return "/" + templateCode;
		}
		if ("app_native_payCenter".equals(templateCode)) {
			return "/" + templateCode;
		}
		if(StringUtil.isNull(userId)){
			userId=request.getParameter("userId")+"";
		}
		if(StringUtil.isNotNull(userId)){
			tycoinUser = this.tycoinUserService.findById(Long.valueOf(userId));
		}

		if (tycoinUser == null) {
			templateCode = "/app_login";
		}
		if ("app_Scanner".equals(templateCode)) {

			System.out.println(
					"---------------项目访问的地址为：" + LoadProperties.loadPropertiesValue("applicationURL") + "--------");
			String LogNo = RandomUtils.getRandomString(16);

			String imgUrl = LoadProperties.loadPropertiesValue("applicationURL") + "/tycoinPayApp/app_payIndex";
			imgUrl += "?UserId=" + userId + "&Logno=" + LogNo;
			String filePathImg = "/static/zhifuImg/qr-" + userId + "_" + LogNo + ".png";
			String filePath = String.format(
					SpringContextHolder.getRootRealPath() + "\\static\\zhifuImg\\qr-" + userId + "_" + LogNo + ".png",
					imgUrl);
			System.out.println("filePath:" + filePath);
			File f = new File(filePath);
			if (!f.exists()) {
				ZxingUtils.getQRCodeImge(imgUrl, 256, filePath);
			}
			filePathImg = filePathImg.replace("/static/", "");
			request.setAttribute("filePathCodeImg", filePathImg);
			request.setAttribute("imgUrl", imgUrl);
			request.setAttribute("Logno", LogNo);
		}

		if ("app_withdrawals".equals(templateCode)||"app_jfturn".equals(templateCode)) {
			if(0==tycoinUser.getIsRealname()){
				return "/app_realname";
			}
			
		}
		
		request.setAttribute("tycoinUser", tycoinUser);
		return "/" + templateCode;
	}

	@RequestMapping(value = "/user/login", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String loginUser(HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException {
		String result = "";
		String userName = request.getParameter("userName");
		String passWord = request.getParameter("passWord");
		TycoinUser tycoinUser = new TycoinUser();
		if (PhoneFormatCheckUtils.isChinaPhoneLegal(userName)) {
			    tycoinUser = tycoinUserService.findOneBymobile( userName);
 		} else {
			    tycoinUser  = tycoinUserService.findOneByusername(userName);
		}
		if (tycoinUser != null) {
			String salt = tycoinUser.getSalt();
			MD5Utils encoderMd5 = new MD5Utils(salt, "MD5");
			System.out.println(tycoinUser.getPassword());
			boolean passwordValid = encoderMd5.isPasswordValid(tycoinUser.getPassword(), passWord);
			if (passwordValid) {
				Cookie cookie = new Cookie("userInfo", "userName:" + java.net.URLEncoder.encode(userName, "UTF-8")
						+ ",passWord:" + tycoinUser.getPassword() + ",userId:" + tycoinUser.getId());
				cookie.setMaxAge(7200);
				cookie.setPath("/");
				response.addCookie(cookie);
				request.getSession().setAttribute("userName", userName);
				request.getSession().setAttribute("passWord", tycoinUser.getPassword());
				request.getSession().setAttribute("userId", tycoinUser.getId());
				result = "{\"code\":\"0000\",\"msg\":\"登录成功!\"}";
			} else {
				result = "{\"code\":\"2000\",\"msg\":\"用户名或密码错误!\"}";
			}
		} else {
			result = "{\"code\":\"1000\",\"msg\":\"该用户不存在!\"}";

		}
		return result;
	}

	@RequestMapping(value = "/user/getUserInfo", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody	
	public String getUserInfo(HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException {
		String result = "";
		String userName = String.valueOf(request.getSession().getAttribute("userName"));
		TycoinUser tycoinUser = new TycoinUser();
		if (PhoneFormatCheckUtils.isChinaPhoneLegal(userName)) {
		    tycoinUser = tycoinUserService.findOneBymobile( userName);
		} else {
		    tycoinUser  = tycoinUserService.findOneByusername(userName);
	}
		if (tycoinUser != null) {
			
			JSONObject jsonObject = JSONObject.fromObject(tycoinUser);
			result = jsonObject.toString();
		} else {
			result = "{\"code\":\"1000\",\"msg\":\"改用户不存在!\"}";
		}
		return result;
	}

 
	@RequestMapping(value = "/user/getAccountInfo", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String getAccountInfo(HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException {
		String result = "";
		String userId = String.valueOf(request.getSession().getAttribute("userId"));
		TycoinUser tycoinUser = new TycoinUser();
		tycoinUser = tycoinUserService.findById(Long.valueOf(userId));
		TycoinAccount tycoinAccount = tycoinAccountService.findOneByuserId(userId);

		if (tycoinUser != null) {
			JSONObject jsonObject = JSONObject.fromObject(tycoinAccount);
			result = jsonObject.toString();
		} else {
			result = "{\"code\":\"1000\",\"msg\":\"改用户不存在!\"}";
		}
		return result;
	}

 	@RequestMapping(value = "/user/loadCountLog", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String loadCountLog(HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException {
		String result = ""; 
		String userName = String.valueOf(request.getSession().getAttribute("userName"));
		TycoinUser tycoinUser = new TycoinUser();
		if (PhoneFormatCheckUtils.isChinaPhoneLegal(userName)) {
			tycoinUser = tycoinUserService.findOneBymobile(userName);
		} else {
			tycoinUser = this.tycoinUserService.findOneByusername(userName);
		}
		PageInfo pageInfo =new PageInfo();
		String startIndex = request.getParameter("startIndex");
		String MaxNum = request.getParameter("MaxNum");
		pageInfo.setOrder("-paymentTime");
		int size=Integer.valueOf(MaxNum)-Integer.valueOf(startIndex);
		if (StringUtils.isNotBlank(startIndex) && StringUtils.isNotBlank(MaxNum)) {
			pageInfo.setSize(size);
			pageInfo.setPage(Integer.valueOf(MaxNum)/size-1);
		} else {
			pageInfo.setSize(10);
			pageInfo.setPage(0);
		}
		Map<String, String> parMap = new HashMap<String, String>();
		List<TycoinAccountRecharge> TycoinAccountRechargelist = new ArrayList<TycoinAccountRecharge>();
		if (tycoinUser != null) {
			parMap.put("userId", String.valueOf(tycoinUser.getId()));
			
			TycoinAccountRechargelist = tycoinAccountRechargeService.queryByPage(pageInfo, parMap);
		}
		result = JSONArray.fromObject(parMap).toString();
		return result;
	}
 	
 	
 	@RequestMapping(value = "/user/loadCountLog2", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String loadCountLog2(HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException {
		String result = ""; 
		String userName = String.valueOf(request.getSession().getAttribute("userName"));
		TycoinUser tycoinUser = new TycoinUser();
		if (PhoneFormatCheckUtils.isChinaPhoneLegal(userName)) {
		    tycoinUser = tycoinUserService.findOneBymobile( userName);
		} else {
		    tycoinUser  = tycoinUserService.findOneByusername(userName);
	}
		
		String payMode=request.getParameter("payType");
		String paymentStatus=request.getParameter("paymentStatus");
		

		
		PageInfo pageInfo =new PageInfo();
		String startIndex = request.getParameter("startIndex");
		String MaxNum = request.getParameter("MaxNum");
		pageInfo.setOrder("-paymentTime");
		int size=Integer.valueOf(MaxNum)-Integer.valueOf(startIndex);
		if (StringUtils.isNotBlank(startIndex) && StringUtils.isNotBlank(MaxNum)) {
			pageInfo.setSize(size);
			pageInfo.setPage(Integer.valueOf(MaxNum)/size-1);
		} else {
			pageInfo.setSize(10);
			pageInfo.setPage(0);
		}
		Map<String, String> parMap = new HashMap<String, String>();
		if(!StringUtil.isNull(payMode)){
			parMap.put("payMode", payMode);
		}
		if(!StringUtil.isNull(paymentStatus)){
			parMap.put("paymentStatus", paymentStatus);
		}
		
		
		List<TycoinAccountRecharge> TycoinAccountRechargelist = new ArrayList<TycoinAccountRecharge>();
		if (tycoinUser != null) {
			parMap.put("userId", String.valueOf(tycoinUser.getId()));
			TycoinAccountRechargelist = tycoinAccountRechargeService.queryByPage(pageInfo, parMap);
		}
		result = JSONArray.fromObject(TycoinAccountRechargelist).toString(); 
		return result;
	}
	
	
	
	@RequestMapping(value = "/user/loadCountDetailLog", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String loadCountDetailLog(HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException {
		String result = "";
		String userName = String.valueOf(request.getSession().getAttribute("userName"));
		TycoinUser tycoinUser = new TycoinUser();
		if (PhoneFormatCheckUtils.isChinaPhoneLegal(userName)) {
		    tycoinUser = tycoinUserService.findOneBymobile( userName);
		} else {
		    tycoinUser  = tycoinUserService.findOneByusername(userName);
	}
 		String startIndex = request.getParameter("startIndex");
		String MaxNum = request.getParameter("MaxNum");
 		PageInfo pageInfo=new PageInfo();
		pageInfo.setOrder("-paymentTime");
		int size=Integer.valueOf(MaxNum)-Integer.valueOf(startIndex);
		if (StringUtils.isNotBlank(startIndex) && StringUtils.isNotBlank(MaxNum)) {
			pageInfo.setSize(size);
			pageInfo.setPage(Integer.valueOf(MaxNum)/size-1);
		} else {
			pageInfo.setSize(10);
			pageInfo.setPage(0);
		}
		Map<String, String> parMap = new HashMap<String, String>();
		List<TycoinAccountRecharge> TycoinAccountRechargelist = new ArrayList<TycoinAccountRecharge>();
		if (tycoinUser != null) {
			parMap.put("userId", String.valueOf(tycoinUser.getId()));
			TycoinAccountRechargelist = tycoinAccountRechargeService.queryByPage(pageInfo, parMap);
		}
		
 
		
		
 		result = JSON.toJSONString(TycoinAccountRechargelist);
		return result;
	}

	@RequestMapping(value = "/getChuanglan/Code", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public String getChuanglanCode(HttpServletRequest request, HttpServletResponse response) {
		String result = "";
		String mobile = request.getParameter("mobile");
		String smsContext = request.getParameter("smsContext");
		try {
			result = SmsSendChuangLan.sendChuangLanSms(mobile, smsContext);
		} catch (Exception e) {
		}
		return result;
	}

	@RequestMapping(value = "/user/appScannerImg")
	@ResponseBody
	public String payTypeFactory(HttpServletRequest request, HttpServletResponse response) {
		String result = "";
		String imgUrl = LoadProperties.loadPropertiesValue("applicationURL") + "/tycoinPayApp/app_payIndex";
		String userId = String.valueOf(request.getSession().getAttribute("userId"));
		String LogNo = RandomUtils.getRandomString(16);
		imgUrl += "?userId=" + userId;
		imgUrl += "&Logno=" + LogNo;
		TycoinUser tycoinUser = null;
		if (StringUtils.isNotBlank(userId)) {
			tycoinUser = tycoinUserService.findById(Long.valueOf(userId));
		}
		if (tycoinUser != null) {
			String filePath = String.format(
					SpringContextHolder.getRootRealPath() + "\\static\\zhifuImg\\qr-" + userId + "_" + LogNo + ".png",
					imgUrl);
			System.out.println("filePath:" + filePath);
			ZxingUtils.getQRCodeImge(imgUrl, 256, filePath);
			result = "{\"LogNo\":\"" + LogNo + "\",\"filePath\":\"" + filePath + "\"}";
		} else {
		}
		return result;
	}

	@RequestMapping("/chuangLan/chuangLanSend")
	public String chuangLanSend(Model model, HttpServletRequest request, HttpServletResponse response) {
		List<TycoinChuanglanMsg> list = tycoinChuanglanMsgService.findAll();
		model.addAttribute(list);
		model.addAttribute("tycoinChuanglanList", list);
		return "/chuangLanSend";
	}

	@RequestMapping(value = "/chuangLan/chuangLanAdd", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String chuangLanAdd(TycoinChuanglanMsg chuanglanMsg) {
		String result = "";
		tycoinChuanglanMsgService.save(chuanglanMsg);
		List<TycoinChuanglanMsg> tycoinChuanglanMsgAll = tycoinChuanglanMsgService.findAll();
		result = JSON.toJSONString(tycoinChuanglanMsgAll);
		return result;
	}

	@RequestMapping(value = "/recharge/findRechargeByLogNo", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String findRechargeByLogNo(HttpServletRequest request, HttpServletResponse response) {
		String result = "";
		String Logno = request.getParameter("Logno");
		 TycoinAccountRecharge  tycoinAccountRecharge = tycoinAccountRechargeService.findOneBylogno(Logno);
		if (tycoinAccountRecharge != null ) {
		 
			result = JSON.toJSONString(tycoinAccountRecharge);
		}
		return result;
	}

	// 群发短信
	@RequestMapping(value = "/chuangLan/phoneSend", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String phoneSend(HttpServletRequest request, HttpServletResponse response) {
		String result = "";
		String mobile = request.getParameter("mobile");
		String id = request.getParameter("id");
		String mobiles[] = mobile.split(",");
		for (int i = 0; i < mobiles.length; i++) {
			String time = String.valueOf(request.getSession().getAttribute(mobiles[i]));
			if (time != "null" && time != null) {
				Long historyTime = Long.parseLong(request.getSession().getAttribute(mobiles[i]) + "");
				long s = (System.currentTimeMillis() - historyTime) / (1000 * 60);
				if (s > 30) {
					request.getSession().setAttribute(mobiles[i], System.currentTimeMillis());
				} else {
					Map map = new HashMap<>();
					map.put("code", "201");
					result = JSON.toJSONString(map);
					return result;
				}
			}
		}
		TycoinChuanglanMsg msg = tycoinChuanglanMsgService.findById(Long.valueOf(id));
		try {
			long currentInt = System.currentTimeMillis();
			for (int i = 0; i < mobiles.length; i++) {
				request.getSession().setAttribute(mobiles[i], currentInt);
			}
			result = SmsSendChuangLan.sendChuangLanSms(mobile, msg.getName() + msg.getText());
		} catch (Exception e) {
		}
		return result;
	}

	// 统计每种支付方式
	@RequestMapping(value = "/countLog/accountPay", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String accountPay(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("进入control求人数和钱");
		String result = "";
		String startDay = "";
		String endDay = "";
		// int type = Integer.parseInt(request.getParameter("type") + "");
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = DateUtils.sumDay(-1);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		startDay = map.get("startDay");
		endDay = map.get("endDay");
		String userId = (String) request.getSession().getAttribute("userId");
		List<TycoinAccountRecharge> list = tycoinAccountRechargeService.findaccountPayRechargeToDate(startDay, endDay,
				userId);
		// 循环遍历list
		float summoney1 = 0;
		float summoney2 = 0;
		float summoney3 = 0;
		float summoney4 = 0;
		float summoney5 = 0;
		float summoney6 = 0;
		int count1 = 0;
		int count2 = 0;
		int count3 = 0;
		int count4 = 0;
		int count5 = 0;
		int count6 = 0;
		List<Map> list1 = new ArrayList();
		if (list != null) {
			System.out.println("list的长度是" + list.size());
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getPayMode() == 2) {
					// 求每种方式的金额
					summoney2 = AmountUtil.add(summoney2+"", (list.get(i).getMoneyfloat())+"").floatValue();
					count2++;
					System.out.println(summoney2);
					// 统计用户的数量
				} else if (list.get(i).getPayMode() == 3) {
					summoney3 = AmountUtil.add(summoney3+"", (list.get(i).getMoneyfloat())+"").floatValue();
					count3++;
					System.out.println(summoney3);
				} else if (list.get(i).getPayMode() == 1) {
					summoney1 = AmountUtil.add(summoney1+"", (list.get(i).getMoneyfloat())+"").floatValue();
					count1++;
					System.out.println(summoney1);
				} else if (list.get(i).getPayMode() == 4) {
					summoney4 = AmountUtil.add(summoney4+"", (list.get(i).getMoneyfloat())+"").floatValue();
					count4++;
				} else if (list.get(i).getPayMode() == 5) {
					summoney5 = AmountUtil.add(summoney5+"", (list.get(i).getMoneyfloat())+"").floatValue();
					count5++;
				} else if (list.get(i).getPayMode() == 6) {
					summoney6 = AmountUtil.add(summoney6+"", (list.get(i).getMoneyfloat())+"").floatValue();
					count6++;
				}
				
			}
		}

		Map<String, Object> zfbMap = new HashMap<>();
		zfbMap.put("summoney2", summoney2);
		zfbMap.put("count2", count2);
		zfbMap.put("paymode2", 2);
		Map<String, Object> baiduMap = new HashMap<>();
		baiduMap.put("summoney3", summoney3);
		baiduMap.put("count3", count3);
		baiduMap.put("paymode3", 3);
		Map<String, Object> weixin = new HashMap<>();
		weixin.put("summoney1", summoney1);
		weixin.put("count1", count1);
		weixin.put("paymode1", 1);
		Map<String, Object> qqmap = new HashMap<>();
		qqmap.put("summoney4", summoney4);
		qqmap.put("count4", count4);
		qqmap.put("paymode4", 4);
		Map<String, Object> jingdongmap = new HashMap<>();
		jingdongmap.put("summoney5", summoney5);
		jingdongmap.put("count5", count5);
		jingdongmap.put("paymode5", 5);
		Map<String, Object> unionmap = new HashMap<>();
		unionmap.put("summoney6", summoney6);
		unionmap.put("count6", count6);
		unionmap.put("paymode6", 6);

		list1.add(zfbMap);
		list1.add(baiduMap);
		list1.add(weixin);
		list1.add(qqmap);
		list1.add(jingdongmap);
		list1.add(unionmap);

		result = JSON.toJSONString(list1);
		System.err.println(result);
		return result;
	}

	// 查询时间
	@RequestMapping(value = "/countLog/findBingRechargeToDate", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String findBingRechargeToDate(HttpServletRequest request, HttpServletResponse response) {
 		String result = "";
		String startDay = "";
		String endDay = "";
		int type = Integer.parseInt(request.getParameter("type") + "");
		Map<String, String> map = new HashMap<String, String>();

		if (type == 1) {
			try {
				map = DateUtils.sumDay(-1);
				} catch (ParseException e) {
			}
			startDay = map.get("startDay");
			endDay = map.get("endDay");
		} else if (type == 2) {
			try {
				map = DateUtils.sumDay(-7);
				} catch (ParseException e) {
			}
			startDay = map.get("startDay");
			endDay = map.get("endDay");
		} else if (type == 3) {
			try {
				map = DateUtils.sumDay(-30);
				} catch (ParseException e) {
			}
			startDay = map.get("startDay");
			endDay = map.get("endDay");
		}

		String userId =String.valueOf(request.getSession().getAttribute("userId"));
		List<TycoinAccountRecharge> list = tycoinAccountRechargeService.findBingRechargeToDate(startDay, endDay, userId);
		// 循环遍历list
		double count1 = 0;
		double count2 = 0;
		double count3 = 0;
		double count4 = 0;
		double count5 = 0;
		double count6 = 0;
		List list1 = new ArrayList();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getPayMode() == 1) {
					count1 += list.get(i).getMoneyfloat();
				} else if (list.get(i).getPayMode() == 2) {
					count2 += list.get(i).getMoneyfloat();
				} else if (list.get(i).getPayMode() == 3) {
					count3 += list.get(i).getMoneyfloat();
				} else if (list.get(i).getPayMode() == 4) {
					count4 += list.get(i).getMoneyfloat();
				} else if (list.get(i).getPayMode() == 5) {
					count5 += list.get(i).getMoneyfloat();
				} else if (list.get(i).getPayMode() == 6) {
					count6 += list.get(i).getMoneyfloat();
				}
			}
		}
		double sumCount = count1 + count2 + count3 + count4 + count5 +count6;
		list1.add(count1 / sumCount);
		list1.add(count2 / sumCount);
		list1.add(count3 / sumCount);
		list1.add(count4 / sumCount);
		list1.add(count5 / sumCount);
		list1.add(count6 / sumCount);
 		result = JSON.toJSONString(list1);
		return result;
	}

	// 折线图查询时间
	// 查询时间

	@RequestMapping(value = "/countLog/findLineRechargeToDate", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String findLineRechargeToDate(HttpServletRequest request, HttpServletResponse response) {
		String result = "";
		String type = request.getParameter("type");
		String userId =String.valueOf(request.getSession().getAttribute("userId"));
		Map<String, String> map = new HashMap<String, String>();
		int day = 0;
		if ("1".equals(type)) {
			day = -1;
		} else if ("2".equals(type)) {
			day = -7;
		} else if ("3".equals(type)) {
			day = -30;
		}
		try {
			map = DateUtils.sumDay(day);
		} catch (ParseException e) {
		}
		map.put("userId", userId);

		List<TycoinAccountRecharge> rechargeList = new ArrayList<TycoinAccountRecharge>();
		rechargeList = tycoinAccountRechargeService.findTycoinAccountRechargeByNativeSql(map.get("startDay"),map.get("endDay"),userId);
		Map<String, String> weixinPay = new HashMap<String, String>();
		Map<String, String> aliPay = new HashMap<String, String>();
		Map<String, String> Qqpay = new HashMap<String, String>();
		Map<String, String> BaiduPay = new HashMap<String, String>();
		Map<String, String> JdPay = new HashMap<String, String>();
		Map<String, String> unionPay = new HashMap<String, String>();
		// 设置8个时间段,每个三小时;

		if ("1".equals(type)) {
			weixinPay = sumOneDateLine(rechargeList, "1");
			aliPay = sumOneDateLine(rechargeList, "2");
			Qqpay = sumOneDateLine(rechargeList, "3");
			BaiduPay = sumOneDateLine(rechargeList, "4");
			JdPay = sumOneDateLine(rechargeList, "5");
			unionPay = sumOneDateLine(rechargeList, "6");
		}
		if ("2".equals(type)) {
			weixinPay = sumWeekDateLine(rechargeList, "1");
			aliPay = sumWeekDateLine(rechargeList, "2");
			Qqpay = sumWeekDateLine(rechargeList, "3");
			BaiduPay = sumWeekDateLine(rechargeList, "4");
			JdPay = sumWeekDateLine(rechargeList, "5");
			unionPay = sumWeekDateLine(rechargeList, "6");
		}
		if ("3".equals(type)) {
			weixinPay = sumMouthDateLine(rechargeList, "1");
			aliPay = sumMouthDateLine(rechargeList, "2");
			Qqpay = sumMouthDateLine(rechargeList, "3");
			BaiduPay = sumMouthDateLine(rechargeList, "4");
			JdPay = sumMouthDateLine(rechargeList, "5");
			unionPay = sumMouthDateLine(rechargeList, "6");
		}
		List listmap = new ArrayList();
		listmap.add(sortMapByKey(weixinPay));
		listmap.add(sortMapByKey(aliPay));
		listmap.add(sortMapByKey(Qqpay));
		listmap.add(sortMapByKey(BaiduPay));
		listmap.add(sortMapByKey(JdPay));
		listmap.add(sortMapByKey(unionPay));
		JSONArray jsonArray = JSONArray.fromObject(listmap);
 		return jsonArray.toString();
	}

	/**
	 * 积分、佣金查询
	 * 
	 * @param args
	 */

	@RequestMapping(value = "/user/integral", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String integral(HttpServletRequest request) {
		String result = "";
		Map<String, Object> json = new HashMap<String, Object>();
		String userId = String.valueOf(request.getSession().getAttribute("userId"));
		if (userId == "null") {
			json.put("code", "1000");
			result = JSON.toJSONString(json);
		} else {
			TycoinAccount tycoinAccount = tycoinAccountService.findOneByuserId(userId);
			result = JSON.toJSONString(tycoinAccount);
		}
		return result;
	}

	/**
	 * 修改个人信息
	 * @param request
	 * @param nameValue
	 * @param name
	 * @return
	 */
	@RequestMapping(value = "/user/updateUserInfo", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String updateInfo(HttpServletRequest request, String nameValue, String name)
	{
 		String result = "";
		Map<String, Object> json = new HashMap<String, Object>();
		String userId = (String) request.getSession().getAttribute("userId"); 
		if (userId == "null") {
			json.put("code", "1000");
			result = JSON.toJSONString(json);
		} else {
			TycoinUser tycoinUser = this.tycoinUserService.findById(Long.valueOf(userId));
			if ("nickname".equals(name)) {
				tycoinUser.setNickname(nameValue);
			} else if ("gender".equals(name)) {
				tycoinUser.setSex(Integer.parseInt(nameValue));
			} else if ("birth".equals(name)) {
				String time[] = nameValue.split("-");
				tycoinUser.setBirthyear(Short.parseShort(time[0]));
				tycoinUser.setBirthmonth(Short.parseShort(time[1]));
				tycoinUser.setBirthday(Short.parseShort(time[2]));
			} else if ("weixin".equals(name)) {
				tycoinUser.setWeixin(nameValue);
			}
			tycoinUserService.save(tycoinUser);
			json.put("code", "200");
			result = JSON.toJSONString(json);
		}
		return result;
	}

	/**
	 * 银行卡添加
	 * 
	 * @param args
	 */
	@RequestMapping(value = "/bank/addBankCard", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String addBankCard(HttpServletRequest request) {
		String result = "";
		Map<String, Object> json = new HashMap<String, Object>();
		String userId = (String) request.getSession().getAttribute("userId");
		 TycoinUserBank tycoinUserBank=new  TycoinUserBank();
		 	
			String bankUser = request.getParameter("bankUser");
			String bankMobile = request.getParameter("bankMobile");
			String showCityPicker = request.getParameter("showCityPicker");
			String branchName = request.getParameter("branchName");
			String bankCode = request.getParameter("bankCode");
			String cardNo = request.getParameter("cardNo");
			String bankName = request.getParameter("bankName");
			
			TycoinUserBank tycoinUserBanks = tycoinUserBankService.findOneBycardNo(cardNo);
			if(tycoinUserBanks!=null){
				json.put("code", "201");
				json.put("msg", "银行卡已存在");
				result = JSON.toJSONString(json);
			}else{
				if (userId == "null") {
					json.put("code", "1000");
					result = JSON.toJSONString(json);
				} else {
					String[] add = showCityPicker.split(" ");
					tycoinUserBank.setProvince(add[0]);
					tycoinUserBank.setCity(add[1]);
					tycoinUserBank.setBankUser(bankUser);
					tycoinUserBank.setBankMobile(bankMobile);
					tycoinUserBank.setBankCode(bankCode);
					tycoinUserBank.setCardNo(cardNo);
		 			tycoinUserBank.setUserId(userId);
		 			tycoinUserBank.setBranchName(branchName);
		 			tycoinUserBank.setBankName(bankName);
		   			tycoinUserBank.setAddip("127.0.0.1");
		   			long temp=System.currentTimeMillis();
		 			//tycoinUserBank.setAddtime(temp);
					tycoinUserBankService.save(tycoinUserBank);
					json.put("code", "200");
					result = JSON.toJSONString(json);
				}
			}
		
		return result;
	}

	/**
	 * 修改密码
	 * 
	 * @param args
	 */
	@RequestMapping(value = "/user/updatePassWord", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String updatePassWord(HttpServletRequest request, String newPassWord, String

	repeatPassWord, String oldPassWord, String code) {
		String result = "";
		Map<String, Object> json = new HashMap<String, Object>();
		String userId = request.getSession().getAttribute("userId") + "";
		String SessionCode = request.getSession().getAttribute("code") + "";
		String equsetTime = request.getSession().getAttribute("time_" + SessionCode) + "";
		long time;
		if (!"null".equals(equsetTime)) {
			time = Long.parseLong(equsetTime);
		} else {
			time = 0;
			json.put("code", "205");
			result = JSON.toJSONString(json);
			return result;
		}
		Long currentTime = System.currentTimeMillis();
		String yzCode = request.getSession().getAttribute("code_" + SessionCode) + "";
		TycoinUser tycoinUser = new TycoinUser();
		if (StringUtils.isNotBlank(userId)) {
			tycoinUser = tycoinUserService.findById(Long.valueOf(userId));
		} else {
			json.put("code", "1000");
			result = JSON.toJSONString(json);
			return result;
		}
		request.getSession().setAttribute("code", Integer.parseInt(SessionCode) + 1);

		String salt = tycoinUser.getSalt();
		MD5Utils encoderMd5 = new MD5Utils(salt, "MD5");
		System.out.println(tycoinUser.getPassword());
		boolean passwordValid = encoderMd5.isPasswordValid(tycoinUser.getPassword(), oldPassWord);
		if (!repeatPassWord.equals(newPassWord)) {
			// 两次密码比较
			json.put("code", "204");
			result = JSON.toJSONString(json);
			return result;
		}
		if (!passwordValid) {
			// 原始密码错误
			json.put("code", "201");
			result = JSON.toJSONString(json);
			return result;
		} else {
			// 验证
			if ((currentTime - time) / (1000 * 60) > 5) {
				// 验证码失效
				json.put("code", "202");
				result = JSON.toJSONString(json);
				return result;
			} else if (!(yzCode.equals(code))) {
				// 验证码错误
				json.put("code", "203");
				result = JSON.toJSONString(json);
				return result;
			} else {
				tycoinUser.setPassword(encoderMd5.encode(newPassWord));
				tycoinUserService.save(tycoinUser);
				json.put("code", "000");
				result = JSON.toJSONString(json);
				return result;
			}
		}
	}

	/**
	 * 修改密码--发送验证码
	 * 
	 * @param args
	 */
	@RequestMapping(value = "/user/sendCode", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String sendPassWord(HttpServletRequest request, String mobile) {
		String result = "";
		Map<String, Object> json = new HashMap<String, Object>();
		String userId = (String) request.getSession().getAttribute("userId");
		TycoinUser tycoinUser = new TycoinUser();
		if (StringUtils.isNotBlank(userId)) {
			tycoinUser = tycoinUserService.findById(Long.valueOf(userId));
			if (!mobile.equals(tycoinUser.getMobile())) {
				// 手机号不匹配
				json.put("code", "201");
				result = JSON.toJSONString(json);
				return result;
			}

			String SessionCode = String.valueOf(request.getSession().getAttribute("code"));
			if ("null".equals(SessionCode)) {
				request.getSession().setAttribute("code", 1000);
				SessionCode = "1000";
			}
			String notifCode = DateUtils.getYzm();
			long current = System.currentTimeMillis();
			System.out.println(notifCode);
			request.getSession().setAttribute("code_" + SessionCode, notifCode);
			request.getSession().setAttribute("time_" + SessionCode, current);

			String chuanglanStr = "";
			try {

				chuanglanStr = SmsSendChuangLan.sendChuangLanSms(tycoinUser.getMobile(), notifCode);

				result = JSONObject.fromObject(chuanglanStr).toString();
				System.out.println(result);
			} catch (Exception e) {

			}
		} else {
			json.put("code", "404");
			result = JSONObject.fromObject(json).toString();
		}
		return result;
	}

	/**
	 * 忘记密码--发送验证码
	 * 
	 * @param args
	 */
	@RequestMapping(value = "/user/backSendCode", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String backSendCode(HttpServletRequest request, String mobile) {
		String result = "";
		Map<String, Object> json = new HashMap<String, Object>();
		TycoinUser tycoinUser = tycoinUserService.findOneBymobile(mobile);
		if (tycoinUser == null) {
			// 手机号不存在！
			json.put("code", "201");
			result = JSON.toJSONString(json);
			return result;
		}

		String SessionCode = String.valueOf(request.getSession().getAttribute("code"));
		if ("null".equals(SessionCode)) {
			request.getSession().setAttribute("code", 1000);
			SessionCode = "1000";
		}
		String notifCode = DateUtils.getYzm();
		long current = System.currentTimeMillis();
		System.out.println(notifCode);
		request.getSession().setAttribute("code_" + SessionCode, notifCode);
		request.getSession().setAttribute("time_" + SessionCode, current);

		String chuanglanStr = "";
		try {

			chuanglanStr = SmsSendChuangLan.sendChuangLanSms(tycoinUser.getMobile(), notifCode);

			result = JSONObject.fromObject(chuanglanStr).toString();
			System.out.println(result);
		} catch (Exception e) {

		}

		return result;
	}

	/**
	 * 验证动态码--公用方法
	 * 
	 * @param args
	 */
	@RequestMapping(value = "/user/notifyCode", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String notifyCode(HttpServletRequest request, HttpServletResponse response) {
		String result = "";
		Map<String, Object> json = new HashMap<String, Object>();
		String SessionCode = String.valueOf(request.getSession().getAttribute("code"));
		String equsetTime = String.valueOf(request.getSession().getAttribute("time_" + SessionCode));
		String code = request.getParameter("code");
		long time;
		if (!"null".equals(equsetTime)) {
			time = Long.parseLong(equsetTime);
		} else {
			//验证码过期
			time = 0;
			json.put("code", "205");
			result = JSON.toJSONString(json);
			return result;
		}
		Long currentTime = System.currentTimeMillis();
		String yzCode = request.getSession().getAttribute("code_" + SessionCode) + "";

		request.getSession().setAttribute("code", Integer.parseInt(SessionCode) + 1);
		// 验证
		if (!(yzCode.equals(code))) {
			// 验证码错误
			json.put("code", "203");
			result = JSON.toJSONString(json);
			return result;
			
		} else if ((currentTime - time) / (1000 * 60) > 5) {
			// 验证码失效
			json.put("code", "202");
			result = JSON.toJSONString(json);
			return result;
		} else {
			json.put("code", "000");
			result = JSON.toJSONString(json);
			return result;

		}
	}

	/**
	 * 上传图片--个人图片
	 * 
	 * @param args
	 */

	@RequestMapping(value = "/picture/updatePicture", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> pUpdatePicture(HttpServletRequest request, HttpServletResponse response,
			@RequestPart MultipartFile myfile,Integer userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		/*
		 * System.out.println(myfile.getOriginalFilename()); String
		 * name[]=myfile.getOriginalFilename().split(".");
		 * if(!"jps".equals(name) && !"png".equals(name)){ map.put("code", 201);
		 * map.put("msg", "图片类型错误"); }
		 */
		String userIds = userId + "";
		String imgPath = "";
		if(!StringUtil.isNull(userIds)){
			try {
				imgPath = UploadUtil.uploadImg1(myfile, request, StaticVariable.USERIMAGE, "user_");
			} catch (Exception e) {
				e.printStackTrace();
				map.put("code", 203);
				map.put("msg", "上传失败");
			}
			if (!StringUtil.isNull(imgPath)) {
				TycoinUser tycoinUser =  tycoinUserService.findById(Long.valueOf(userId));
				tycoinUser.setAvatar(imgPath);				
				tycoinUserService.save(tycoinUser);
				map.put("code", 200);
				map.put("msg", "上传成功");
				map.put("path", imgPath);
			} else {
				map.put("code", 201);
				map.put("msg", "路径不能为空");
			}
		}else{
			map.put("code", 202);
			map.put("msg", "userId不能为空");
		}
		
		return map;
	}

	/**
	 * 多张上传--身份证 
	 * @param request
	 * @param response
	 * @param myfile
	 * @return
	 */
	@RequestMapping(value = "/picture/idUpdatePicture", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> iUpdatePicture(HttpServletRequest request, HttpServletResponse response,
			@RequestPart(required=false) MultipartFile positiveFile, @RequestPart(required=false) MultipartFile negativeFile,Integer userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		String positiveFilePath = "";
		String negativeFilePath = "";
		//正面验证
		if (positiveFile!=null && !positiveFile.isEmpty()) {
			try {
				positiveFilePath = UploadUtil.uploadImg1(positiveFile, request, StaticVariable.IDCARDIMAGE,
						"positive_");
				System.out.println("code:200");
				map.put("code", "200");
				map.put("path", positiveFilePath);
				map.put("msg", "上传成功");
 			} catch (Exception e) {			
 				e.printStackTrace();
 				map.put("code", "201");
				map.put("msg", "正面上传失败！");
			}
			
		}
		//反面验证
		if (negativeFile!=null && !negativeFile.isEmpty()) {
			try {
				negativeFilePath = UploadUtil.uploadImg1(negativeFile, request, StaticVariable.IDCARDIMAGE,
						"negative_");
				map.put("code", "200");
				map.put("path", negativeFilePath);
				map.put("msg", "上传成功");
			} catch (Exception e) {
				e.printStackTrace();
				map.put("code", "201");
				map.put("msg", "反面上传失败！");
			}			
		}
		System.out.println("code:"+map.get("code"));

		return map;
	}

	/**
	 * 实名认证提交
	 * @param request
	 * @param positivePath
	 * @param negativePath
	 * @return
	 */
	@RequestMapping(value = "/user/verificationIdCard", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> verificationIdCard(HttpServletRequest request,String positivePath,String negativePath,Integer userId){
		Map<String, Object> json=new HashMap<>();
		if(!StringUtil.isNull(positivePath) && !StringUtil.isNull(negativePath)){
			String realPath = request.getSession().getServletContext().getRealPath("");			
			String userIds=userId+"";
			System.out.println(userIds);
			File file1=new File(realPath+positivePath);			
			if(file1.exists()){
				json.put("code", "202");
				json.put("msg", "正面证件不存在");
			}else if(!StringUtil.isNull(userIds)){
				TycoinUser tycoinUser =  tycoinUserService.findById(Long.valueOf(userId));
				//验证正面
				Long start=System.currentTimeMillis();
				System.out.println();
				org.json.JSONObject json1=Verification.VerificationIdCardOcr(realPath+"/"+positivePath, 0);
				Long end=System.currentTimeMillis();
				System.out.println("查询时间共费："+(end-start));
				try {
					String msg1=json1.getString("errorcode");					
					if("0".equals(msg1)){					
						TycoinUserRealnamePic entity=new TycoinUserRealnamePic();
						entity.setAddip("127.0.0.1");
						entity.setAddtime(System.currentTimeMillis());
						entity.setFormat_date(DateUtils.getSystemTime());
						entity.setUserId(Integer.parseInt(userIds));
						entity.setCardPic1(positivePath);
						entity.setCardPic2(negativePath);
						tycoinUserRealnamePicService.save(entity);
						tycoinUser.setIsRealname(0);
						tycoinUserService.save(tycoinUser);
						
						json.put("code","200");
						json.put("msg","验证成功");						
					}else{						
						json.put("code", "205");
						json.put("msg", "验证失败");
					}
				} catch (org.json.JSONException e) {					
					e.printStackTrace();
				}
			}else{
				json.put("code", "204");
				json.put("msg", "userId不在Seesion中");
			}						
		}else{
			json.put("code", "201");
			json.put("msg", "上传失败，路径不能为空");
		}
		return  json;
	}
	
	
	
	
	/**
	 * 
	 * @param request
	 *            接受域
	 * @param response
	 *            响应域
	 * @param fileSignFace
	 *            付款拍照
	 * @param fileSignDraweeDiv
	 *            收款人签字截屏
	 * @param fileSignPayerDiv
	 *            付款人签字截屏
	 * @param fileSignDraweeName
	 *            收款人签字照相
	 * @param fileSignPayerName
	 *            付款人签字照相
	 * @param userId
	 *            用户id
	 * @param paymentId
	 *            第三方支付订单号
	 * @return
	 */
	@RequestMapping(value = "/picture/userSignUpdatePicture", method = RequestMethod.POST)
	@ResponseBody
	public String userSignUpdatePicture(HttpServletRequest request, HttpServletResponse response,
			@RequestPart(value = "SignFace", required = false) MultipartFile fileSignFace,
			@RequestPart(value = "SignDraweeDiv", required = false) MultipartFile fileSignDraweeDiv,
			@RequestPart(value = "SignPayerDiv", required = false) MultipartFile fileSignPayerDiv,
			@RequestPart(value = "SignDraweeName", required = false) MultipartFile fileSignDraweeName,
			@RequestPart(value = "SignPayerName", required = false) MultipartFile fileSignPayerName, Integer userId,
			String paymentId) {
		Map<String, Object> map = new HashMap<String, Object>();
		String reuslt = "";
		if (userId == null) {
			map.put("code", 204);
			map.put("msg", "userId不能为空");
			reuslt = JSON.toJSONString(map);
			return reuslt;
		}
		if (StringUtil.isNull(paymentId)) {
			map.put("code", 204);
			map.put("msg", "paymentId不能为空");
			reuslt = JSON.toJSONString(map);
			return reuslt;
		}
		System.out.println(userId + "-------------------------" + paymentId);

		System.out.println("------------我已经进入图片保存的业务开始：----------");
		if (fileSignFace.isEmpty() || fileSignDraweeDiv.isEmpty() || fileSignPayerDiv.isEmpty()
				|| fileSignDraweeName.isEmpty() || fileSignPayerName.isEmpty()) {
			map.put("code", "201");
			map.put("msg", "请上传五张照片");
			reuslt = JSON.toJSONString(map);
			return reuslt;
		}

		JSONObject signImglist;
		paymentId = paymentId.replaceAll("\"", "");
		System.out.println("外部订单号：" + paymentId);
		TycoinAccountRecharge entity = tycoinAccountRechargeService.findOneBypaymentId(paymentId);
		List<String> filesPathList = new ArrayList<String>();
		if(entity!=null){
			try {
				List<MultipartFile> files = new ArrayList<MultipartFile>();
				files.add(fileSignFace);
				files.add(fileSignDraweeDiv);
				files.add(fileSignPayerDiv);				
				files.add(fileSignDraweeName);
				files.add(fileSignPayerName);
				
				filesPathList = UploadUtil.uploadImg4(files, request, StaticVariable.FACEIMG, userId);
				map.put("SignFace", filesPathList.get(0));
				map.put("SignDraweeDiv", filesPathList.get(1));
				map.put("SignPayerDiv", filesPathList.get(2));
				map.put("SignDraweeName", filesPathList.get(3));
				map.put("SignPayerName", filesPathList.get(4));
				entity.setDraweeSign(1);
				entity.setPayerSign(1);
				signImglist = JSONObject.fromObject(map);
			} catch (Exception e) {
				map.put("code", "202");
				map.put("msg", "图片异常--上传失败");
				reuslt = JSON.toJSONString(map);
				return reuslt;
			}
		}else{
			map.put("code", "203");
			map.put("msg", "订单不存在");
			reuslt = JSON.toJSONString(map);
			return reuslt;
		}
		
		entity.setSignImglist(signImglist.toString());
		tycoinAccountRechargeService.save(entity);
		if (map != null && !("201".equals(map.get("code")))) {
			map.put("code", "200");
			map.put("msg", "上传成功");
		}
		reuslt = JSON.toJSONString(map);
		System.out.println("打印结果：" + reuslt);
		return reuslt;
	}

	public static Map<String, String> sumOneDateLine(List<TycoinAccountRecharge> rechargeList, String payModepar) {
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < 24; i++) {
			map.put(String.valueOf(i), "0");
		}
		if (rechargeList != null && rechargeList.size() > 0) {
			for (TycoinAccountRecharge tycoinAccountRecharge : rechargeList) {
  				String PayModel =String.valueOf(tycoinAccountRecharge.getPayMode());
				if (payModepar.equals(PayModel)) {
					String paymentTime = tycoinAccountRecharge.getPaymentTime();
					String money = tycoinAccountRecharge.getMoney();
					paymentTime = paymentTime.substring(11, 13);
					int paymentTimeInt = Integer.valueOf(paymentTime);
					for (int n = 0; n < 24; n++) {
						if (paymentTimeInt == n) {
							String count = map.get(String.valueOf(n));
							map.put(String.valueOf(n), String.valueOf(Float.valueOf(count) + Float.valueOf(money)));
						}
					}
				}
			}
		}
		return map;

	}

	public static Map<String, String> sumWeekDateLine(List<TycoinAccountRecharge> rechargeList, String payModepar) {
		Map<String, String> map = new HashMap<String, String>();
		Calendar c = Calendar.getInstance();
		int dateNow = c.get(Calendar.DATE);
		int maxDay = DateUtils.getDaysInOneMonth(c.get(Calendar.YEAR), c.get(Calendar.MONTH) - 1);

		for (int i = 1; i < 8; i++) {
			if (dateNow > 8) {
				map.put(String.valueOf(dateNow - i), "0");
			} else {
				if (dateNow - i > 1) {
					map.put(String.valueOf(dateNow - i), "0");
				} else {
					map.put(String.valueOf(maxDay), "0");
					maxDay--;
				}
			}
		}
		if (rechargeList != null && rechargeList.size() > 0) {
			for (TycoinAccountRecharge tycoinAccountRecharge : rechargeList) {
 				int oldpaymentTime = 0;
				boolean bo = false;
				String PayModel =String.valueOf(tycoinAccountRecharge.getPayMode());
				if (payModepar.equals(PayModel)) {
					String paymentTime = tycoinAccountRecharge.getPaymentTime();
					String money = tycoinAccountRecharge.getMoney();
					paymentTime = paymentTime.substring(8, 10);
					for (String key : map.keySet()) {
						if (Integer.valueOf(key) == Integer.valueOf(paymentTime)) {
							String count = map.get(String.valueOf(Integer.valueOf(key)));
							map.put(String.valueOf(Integer.valueOf(key)),
									String.valueOf(Float.valueOf(count) + Float.valueOf(money)));
						}
					}
				}
			}
		}
		return map;

	}

	public static Map<String, String> sumMouthDateLine(List<TycoinAccountRecharge> rechargeList, String payModepar) {
		Map<String, String> map = new HashMap<String, String>();
		Calendar c = Calendar.getInstance();
		int dateNow = c.get(Calendar.DATE);
		int maxDay = DateUtils.getDaysInOneMonth(c.get(Calendar.YEAR), c.get(Calendar.MONTH) - 1);

		for (int i = 1; i < 31; i++) {
			if (dateNow > 30) {
				map.put(String.valueOf(dateNow - i), "0");
			} else {
				if (dateNow - i > 1) {
					map.put(String.valueOf(dateNow - i), "0");
				} else {
					map.put(String.valueOf(maxDay), "0");
					maxDay--;
				}
			}
		}
		if (rechargeList != null && rechargeList.size() > 0) {
			for (TycoinAccountRecharge tycoinAccountRecharge : rechargeList) {
 				String PayModel = String.valueOf(tycoinAccountRecharge.getPayMode());
				if (payModepar.equals(PayModel)) {
					String paymentTime = tycoinAccountRecharge.getPaymentTime();
					String money = tycoinAccountRecharge.getMoney();
					paymentTime = paymentTime.substring(8, 10);
					for (String key : map.keySet()) {
						if (Integer.valueOf(key) == Integer.valueOf(paymentTime)) {
							String count = map.get(String.valueOf(Integer.valueOf(key)));
							map.put(String.valueOf(Integer.valueOf(key)),
									String.valueOf(Float.valueOf(count) + Float.valueOf(money)));
						}
					}
				}
			}
		}
		return map;

	}

	public Map<String, String> sortMapByKey(Map<String, String> oriMap) {
		if (oriMap == null || oriMap.isEmpty()) {
			return null;
		}
		Map<String, String> sortedMap = new TreeMap<String, String>(new Comparator<String>() {
			public int compare(String key1, String key2) {
				int intKey1 = 0, intKey2 = 0;
				try {
					intKey1 = getInt(key1);
					intKey2 = getInt(key2);
				} catch (Exception e) {
					intKey1 = 0;
					intKey2 = 0;
				}
				return intKey1 - intKey2;
			}
		});
		sortedMap.putAll(oriMap);
		return sortedMap;
	}

	private int getInt(String str) {
		int i = 0;
		try {
			Pattern p = Pattern.compile("^\\d+");
			Matcher m = p.matcher(str);
			if (m.find()) {
				i = Integer.valueOf(m.group());
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return i;
	}
  

 	
	//查询账单信息 
	@RequestMapping(value = "/findTransferAccountsInfo", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public String findTransferAccountsInfo(HttpServletRequest request, HttpServletResponse response) {
		String result = ""; 

		
		Long countLogId=Long.valueOf(request.getParameter("countLogId"));
		String userId=request.getParameter("userId");
 		
		 TycoinAccountRecharge  tycoinAccountRecharge = tycoinAccountRechargeService.findTransferAccountsInfo(Long.valueOf(countLogId),userId);
		 TycoinUser tycoinUser =tycoinUserService.findById(Long.valueOf(userId));
		   Map<String,Object>  map = new HashMap<String,Object>();
		   if(tycoinAccountRecharge!=null){
		   map.put("imgs",tycoinAccountRecharge.getSignImglist());
		   map.put("userInfo", tycoinUser);
		   map.put("tycoinAccountRecharge", tycoinAccountRecharge);
		   }
		   String urlPort=LoadProperties.loadPropertiesValue("applicationURL")+"/tycoinPayApp/app_countLogDetail2?countLogId="+countLogId+"&userId="+userId;
		   String filePath = request.getSession().getServletContext().getRealPath("")+ "\\static\\RechargeInfo\\RInfo_" + tycoinAccountRecharge.getId() + "_" + tycoinAccountRecharge.getLogno() + ".png";
		   String fileRoute="static/RechargeInfo/RInfo_" + tycoinAccountRecharge.getId() + "_" + tycoinAccountRecharge.getLogno() + ".png";
		   System.out.println("filePath:" + filePath);
		   System.out.println("urlPort:" + urlPort);
		   File f = new File(filePath); 
		   System.out.println("文件是否存在："+f.exists());
			if (!f.exists()) {
				ZxingUtils.getQRCodeImge(urlPort, 256, filePath);
				map.put("urlImg", fileRoute);
			}else{
				map.put("urlImg", fileRoute);
			}
			map.put("urlPort", urlPort);
 		   
  		return JSON.toJSONString(map);
	} 
	
	/**
	 * 退出当前帐号
	 * 
	 * @return
	 */
	@RequestMapping(value = "/user/exit", method = RequestMethod.GET)
	public String exit(HttpServletRequest request, HttpServletResponse response) {
		request.getSession().removeAttribute("userName");
		request.getSession().removeAttribute("passWord");
		request.getSession().removeAttribute("userId");
		Cookie cookie = new Cookie("userInfo", null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
		return "/app_login";
	}

 
 
	/**
	 * 提现 userId:用户id cash_ithdrawals:提现金额 bankId:银行卡id
	 */

	@RequestMapping(value = "/account/withdrawals", method = RequestMethod.POST)
	@ResponseBody
	public String withdrawals(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> json = new HashMap<>();
		String result = "";
		String userId = String.valueOf(request.getSession().getAttribute("userId"));
		String cash_ithdrawals = request.getParameter("cash_ithdrawals");
		String bankId = request.getParameter("bankId");
		String batchNo = Util.generalBatchNo();

		if (StringUtil.isNull(userId)) {
			json.put("code", "204");
			json.put("msg", "请登录");
			result = JSONObject.fromObject(json).toString();
			return result;
		}
		TycoinAccount tycoinAccount = tycoinAccountService.findOneByuserId(userId);
		if (StringUtil.isNull(cash_ithdrawals)) {
			json.put("code", "201");
			json.put("msg", "请填写提现金额");
			result = JSONObject.fromObject(json).toString();
			return result;
		} else {
			String useMoney = String.valueOf(tycoinAccount.getUseMoney());
			if (Integer.parseInt(AmountUtil.quzheng(useMoney).toString()) < Integer.parseInt(cash_ithdrawals)/100) {
				json.put("code", "202");
				json.put("msg", "提现金额不足");
				result = JSONObject.fromObject(json).toString();
				return result;
			}
			// 根据银行卡id查询银行卡
			TycoinUserBank tycoinUserBank = tycoinUserBankService.findById(Long.valueOf(bankId));

			if (tycoinUserBank == null) {
				json.put("code", "205");
				json.put("msg", "银行卡不存在");
				result = JSONObject.fromObject(json).toString();
				return result;
			}

			TycoinUser tycoinUser = tycoinUserService.findById(Long.valueOf(userId));
			TycoinAccountCash accountCash = new TycoinAccountCash();
			accountCash.setUserId(Integer.parseInt(userId));
			accountCash.setType("11");
			accountCash.setLogno(batchNo);
			accountCash.setAccount(tycoinUserBank.getCardNo());
			accountCash.setBankId(Integer.parseInt(bankId));
			accountCash.setStatus(0);
			accountCash.setMoney(new BigDecimal(((float) Integer.parseInt(cash_ithdrawals)) / 100));
			accountCash.setCashWhere(1);
			accountCash.setAddtime(System.currentTimeMillis());
			accountCash.setAddip("127.0.0.1");
			accountCash.setBankId(Integer.parseInt(bankId));
			accountCash.setBank(tycoinUserBank.getBankName());
			accountCash.setBranch(tycoinUserBank.getBranchName());
			accountCash.setCashPhone(tycoinUser.getMobile());
			accountCash.setTNum(1);
			tycoinAccountCashService.save(accountCash);

			System.out.println("----------批次号:" + batchNo + "-----------");
			TycoinAccountPayment tycoinAccountPayment = new TycoinAccountPayment();
			tycoinAccountPayment.setAddip("127.0.0.1");
			tycoinAccountPayment.setAmount(cash_ithdrawals);
			tycoinAccountPayment.setAmountFloat((float) Integer.parseInt(cash_ithdrawals) / 100);
			tycoinAccountPayment.setBankCode("CCB");
			tycoinAccountPayment.setUserId(userId);
			tycoinAccountPayment.setCreateTime(new Date());
			tycoinAccountPayment.setDateTime(Long.valueOf(System.currentTimeMillis()));
			tycoinAccountPayment.setStatus(0);
			tycoinAccountPayment.setPaymentId(batchNo);
			tycoinAccountPaymentService.save(tycoinAccountPayment);

			// 苏宁提现接口调用
			BatchWithdrawDemo batchWithdraw = new BatchWithdrawDemo();
			try {
				/*String responseResult = batchWithdraw.action(tycoinUserBank.getBankUser(),cash_ithdrawals, tycoinUserBank.getBankName(), tycoinUserBank.getCardNo(), tycoinUserBank.getBankCode(),
						batchNo);
				JSONObject resuleJson = JSONObject.fromObject(responseResult);
				JSONObject respArr = JSONObject.fromObject(resuleJson.get(SuNingConfig.merchantNo + "_" + batchNo));
				String responseCode = "";
				if (respArr != null && respArr.size() > 0) {
					responseCode = respArr.getString("responseCode");
				} else {
					responseCode = resuleJson.getString("responseCode");
					respArr = resuleJson;
					System.out.println("打印结果进入——————————————————————————");
					System.out.println(respArr.toString());
					System.out.println("打印结果输出——————————————————————————");
				}*/
				//TODO
				if ("0000".equals("0000")) {

					json.put("code", "200");
					json.put("msg", "申请成功，等待银行处理");
					result = JSONObject.fromObject(json).toString();
					return result;
				} else {
					json.put("code", "203");
					json.put("msg", "受理失败");
					result = JSONObject.fromObject(json).toString();
				}
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}
		return result;

	}

	/**
	 * 获取银行卡
	 */
	@RequestMapping(value = "/bank/getBank", method = RequestMethod.POST)
	@ResponseBody
	public String getBank(HttpServletRequest request, HttpServletResponse response, String id) {
		String result = "";
		Map<String, Object> map = new HashMap<>();
		String userId = String.valueOf(request.getSession().getAttribute("userId"));
		List<TycoinUserBank> tycoinUserBankList = tycoinUserBankService.findByUserIdAll(userId);
 		if (tycoinUserBankList != null && tycoinUserBankList.size() > 0) {
			JSONArray jsonArray = JSONArray.fromObject(tycoinUserBankList);
			result = jsonArray.toString();
		} else {
			map.put("code", "0001");
			map.put("msg", "未绑定银行卡");
			result = JSONObject.fromObject(map).toString();
		}
		return result;
	}

	/**
	 * 收款列表详情
	 */
	@RequestMapping(value = "/countLog/detail", method = RequestMethod.GET)
	public String detail(HttpServletRequest request, HttpServletResponse response,Integer id) {
		String result = "";
		Map<String,Object> map=new HashMap<>();
		String userId=String.valueOf( request.getSession().getAttribute("userId"));
		if(id==null){
			map.put("code", "201");
			map.put("msg", "id不能为空");
			result=JSONObject.fromObject(map).toString();
		}else{
 			TycoinAccountRecharge tycoinAccountRecharge = tycoinAccountRechargeService.findTransferAccountsInfo(id, userId);
 
			result=JSONObject.fromObject(tycoinAccountRecharge).toString();
		}
		return result;
	}
	
	/**
	 * 找回密码
	 * @param request
	 * @param response
	 * @param newPassWord  找回的新密码
	 * @param mobilephone    手机号
	 * @return
	 */
	@RequestMapping(value = "/user/backPassWord", method = RequestMethod.POST)
	@ResponseBody
	public String backPassWord(HttpServletRequest request, HttpServletResponse response,
			String newPassWord,String mobilephone) {
		Map<String,String> json=new HashMap<>();
		String result="";
		if(StringUtil.isNull(newPassWord)|| StringUtil.isNull(mobilephone)){
			json.put("code", "201");
			json.put("msg", "新密码或手机号不能为空");
			result=JSONObject.fromObject(json).toString();
		}else{
			TycoinUser tycoinUser = tycoinUserService.findOneBymobile(mobilephone);
			if(tycoinUser!=null){
				String salt = tycoinUser.getSalt();
				MD5Utils encoderMd5 = new MD5Utils(salt, "MD5");
				System.out.println(tycoinUser.getPassword());
				tycoinUser.setPassword(encoderMd5.encode(newPassWord));
				tycoinUserService.save(tycoinUser);
				json.put("code", "000");
				json.put("msg", "修改成功");
				result=JSONObject.fromObject(json).toString();
			}else{
				json.put("code", "202");
				json.put("msg", "用户不存在");
				result=JSONObject.fromObject(json).toString();
			}
		}
		System.out.println(result);
		logger.debug(result);
		return result;
	}
	
	
	/**
	 * 积分转账
	 * @param request
	 * @param response
	 * @param realname 对方名字
	 * @param mobile 对方手机号
	 * @param money  金额
	 * @param remark  备注
	 * @return
	 */
	@RequestMapping(value="/account/transfer",method=RequestMethod.POST)
	@ResponseBody																			
	public String transfer(HttpServletRequest request,HttpServletResponse response,String realname,String mobile,String money,String remark){
		String result="";
		Map<String,Object> paramMap=new HashMap<String,Object>();		
		String userId=String.valueOf(request.getSession().getAttribute("userId"));
		paramMap.put("userId", userId);
		paramMap.put("realname", realname);
		paramMap.put("mobile", mobile);
		paramMap.put("money", money);
		paramMap.put("remark", remark);
		Map<String,Object> resultmap=tycoinUserTransferAccountService.transferAccount(paramMap);
		result=JSONObject.fromObject(resultmap).toString();
		return result;
	}
	
	/**
	 * 查询转账列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/transfer/list",method=RequestMethod.POST)
	@ResponseBody
	public String transferList(HttpServletRequest request,HttpServletResponse response){
		String result = ""; 
		String userName = String.valueOf(request.getSession().getAttribute("userName"));
		TycoinUser tycoinUser = new TycoinUser();
		if (PhoneFormatCheckUtils.isChinaPhoneLegal(userName)) {
			tycoinUser = tycoinUserService.findOneBymobile(userName);
		} else {
			tycoinUser = this.tycoinUserService.findOneByusername(userName);
		}
		String userId=String.valueOf(request.getSession().getAttribute("userId"));
		Page page = new Page(); 
		String startIndex = request.getParameter("startIndex");
		String MaxNum = request.getParameter("MaxNum");
		if (StringUtils.isNotBlank(startIndex) && StringUtils.isNotBlank(MaxNum)) {
			page.setBeginIndex(Integer.valueOf(startIndex));
			page.setEveryPage(Integer.valueOf(MaxNum));
		} else {
			page.setBeginIndex(0);
			page.setEveryPage(10);
		}
		Map<String, String> parMap = new HashMap<String, String>();
		if(!StringUtil.isNull(userId)){
			parMap.put("userId", userId);
		}
		List<TycoinAccountLog> TycoinAccountLogList = new ArrayList<TycoinAccountLog>();
		if (tycoinUser != null) {
			parMap.put("userId", String.valueOf(tycoinUser.getId()));
			TycoinAccountLogList = tycoinAccountLogService.queryByPage(page, parMap);
		}
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("tycoinAccountLogList", JSONArray.fromObject(TycoinAccountLogList));
 		result = JSONArray.fromObject(map).toString(); 
		return result;
	}
	
	/**
	 * 转账详情信息
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/transfer/details",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> transferDetails(HttpServletRequest request,HttpServletResponse response,Integer id){
		String result = ""; 
		Map<String,Object> json=new HashMap<String,Object>();
		TycoinAccountLog tycoinAccountLog = tycoinAccountLogService.findById(Long.valueOf(id));
		if(tycoinAccountLog!=null){
			json.put("addtime", DateUtils.timeStampTime(Long.parseLong(tycoinAccountLog.getAddtime()+"")));
			json.put("data", tycoinAccountLog);
		}else{
			json.put("code", 201);
			json.put("msg", "查询信息不存在");
		}
		return json;
	}
	
	/**
	 *	查询提现列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/cash/list",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> cashList(HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> result=new HashMap<>();
		String userId=String.valueOf(request.getSession().getAttribute("userId"));
		Page page = new Page(); 
		String startIndex = request.getParameter("startIndex");
		String MaxNum = request.getParameter("MaxNum");
		if (StringUtils.isNotBlank(startIndex) && StringUtils.isNotBlank(MaxNum)) {
			page.setBeginIndex(Integer.valueOf(startIndex));
			page.setEveryPage(Integer.valueOf(MaxNum));
		} else {
			page.setBeginIndex(0);
			page.setEveryPage(10);
		}
		if(StringUtil.isNull(userId)){
			result.put("code", "201");
			result.put("msg", "userId为空");
		}else{
//			List<TycoinAccountCashBankView> accountCashList = tycoinAccountCashBankViewService.getAccountCashList(page.getBeginIndex(), userId);
// 			if(accountCashList!=null  && accountCashList.size()>0){
//				result.put("accountCashList", accountCashList);
//			}else{
//				result.put("code", "2001");
//			}
		}	
		return result;
	}
	
	
	/**
	 * 提现详情信息
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/cash/details",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> cashDetails(HttpServletRequest request,HttpServletResponse response,Long id){
		Map<String,Object> json=new HashMap<String,Object>();
		TycoinAccountCash tycoinAccountCash = tycoinAccountCashService.findById(id);
		TycoinUser tycoinUser=tycoinAccountCash.getTycoinUser();
		TycoinUserBank tycoinUserBank =tycoinUserBankService.findById(Long.valueOf(tycoinAccountCash.getBankId()));
 		Map<String,Object> map=new HashMap<String,Object>();
 		json.put("tycoinUser", tycoinUser);
 		json.put("tycoinAccountCash", tycoinAccountCash);
 		json.put("tycoinUserBank", tycoinUserBank);
 		if(map!=null && map.size()>0){
			json.put("addtime", DateUtils.timeStampTime(Long.parseLong(tycoinAccountCash.getAddtime()+"")));
			json.put("data", map);
		}else{
			json.put("code", 201);
			json.put("msg", "查询信息不存在");
		}
		return json;
	}
	
	/**
	 * 积分转账
	 * @param request
	 * @param response
	 * @param realname 对方名字
	 * @param mobile 对方手机号
	 * @param money  金额
	 * @param remark  备注
	 * @return
	 */
	@RequestMapping(value="/account/cannerMoney", produces = "application/json;charset=UTF-8",method=RequestMethod.POST)
	@ResponseBody																			
	public String cannerMoney(HttpServletRequest request,HttpServletResponse response){
	    	String result="";
	    	String countLogId=request.getParameter("countLogId");
	    	TycoinAccountRecharge tycoinAccountRecharge=tycoinAccountRechargeService.findById(Long.valueOf(countLogId));
	    	boolean bool=tycoinAccountRechargeCallbackProcessService.rechargeRollCallbackProcess(tycoinAccountRecharge,request,response);
         	Map<String,String>  map=new HashMap<String,String>();
	    	if(bool){
	    		map.put("code", "200");
	         }else{
		     	map.put("code", "201");
	         }
	    	result=JSONObject.fromObject(map).toString();
	    	System.out.println("-------cannerMoney的resultJson为："+result+"----");
	    	return result;
	}
 
	
	
}
